<template>
  <transition name="slide">
    <div :class="['co-message', type, center, showClose]" v-if="messageIsVisible">{{ message }}<img @click="close" src="../../../assets/关闭.png" alt=""></div>
  </transition>
</template>

<script>

export default {
  name: 'co-message',
  data () {
    return {
      messageIsVisible: false,
      duration: 3000
    }
  },
  methods: {
    close () {
      new Promise(resolve => {
        this.messageIsVisible = false
        if (!this.messageIsVisible) {
          resolve()
        }
      }).then(() => this.$destroy())
    }
  },
  beforeDestroy () {
  },
  mounted () {
    this.messageIsVisible = true
    // timeout insterval 用完之后是不是都要清除掉
    const timer = setTimeout(() => {
      this.messageIsVisible = false
    }, this.duration)
    this.$once('hook:beforeDestroy', () => {
      // 清除定时器
      clearTimeout(timer)
      // window.console.log('hook:beforeDestroy执行了');
    })
    // 监听组件的生命周期
  }
}
</script>

<style scoped lang="scss">
.co-message{
  position: absolute;
  left: 0;
  right: 0;
  top: 50px;
  line-height: 50px;
  max-width: 400px;
  margin: auto;
  border-radius: 4px;
  color: #909399;
  background-color: #EDF2FC;
  border-color: #909399;
  padding: 0px 15px;
  box-sizing: border-box;
}
.co-message img{
  float: right;
  margin: 18px 10px 0px 0px;
  width: 16px;
}
.co-message__warning {
  color: #E6A23C;
  background-color: #FDF6EC;
  border-color: #E6A23C;
}
.co-message__info {
  color: #909399;
  background-color: #EDF2FC;
  border-color: #909399;
}
.co-message__success {
  color: #67C23A;
  background-color: #F0F9EB;
  border-color: #67C23A;
}
.co-message__error {
  color: #F56C6C;
  background-color: #FEF0F0;
  border-color: #F56C6C;
}
.co-message__warning__showClose img {
  display: block;
}
.co-message__info__showClose img {
  display: block;
}
.co-message__success__showClose img {
  display: block;
}
.co-message__error__showClose img {
  display: block;
}
.co-message__center{
  text-align: center;
}
.slide-enter,.slide-leave-to{
  transform: translateY(-50px);
}
.slide-enter-active,.slide-leave-active{
  transition: all 1s ease-in-out;
}
.slide-enter-to,.slide-leave{
  transform: translateY(0px);
}
</style>
